iT邦幫忙

2025 iThome 鐵人賽

DAY 15
0
自我挑戰組

用 C++ 實作簡易第一人稱視角遊戲:從入門到理解 Ray Casting系列 第 15

Day 15 | Ray Casting : 距離決定牆壁的高矮 - Part 1

  • 分享至 

  • xImage
  •  

大家好~我是鐵匠史密斯
今天我們終於要從「光如何前進」的推導,走到它的第一個實際應用 —— 決定牆壁的高度!
是的,接下來的程式碼,將把光線走過的距離,轉換成牆壁在螢幕上的高矮。

天花板、地板於 screen 上的高度

在昨天的程式中,我們已經能計算 fDistanceToWall(光從玩家出發到撞到牆的距離)。
接下來,讓我們加上兩個關鍵變數:
nCeiling:牆壁的頂端位置(從螢幕上方算下來的行數)
nFloor:牆壁的底端位置(從螢幕上方算下來的行數)
記得,計算機圖學中,垂直方向 y 是由上而下的
由先來一張示意圖,之後的推導會一直需要這張圖~:
https://ithelp.ithome.com.tw/upload/images/20250815/20157653hcW9QVtdHV.png

簡單來說呢:

  • 物體越遠 -> fDistance 越大 -> 牆壁高度變矮
  • 物體越近 -> fDistance 越小 -> 牆壁高度越高
    nCeilingnFloor 的位置是對稱分布的,以螢幕的垂直中心為基準nScreenHeight / 2
    所以,當距離不同時,牆壁的高矮就會自然呈現透視感。

渲染

接著,依照 screen 畫面的垂直位置 y渲染天花板、牆壁以及地板

  • 假設垂直位置 y 小於 nCeiling -> 渲染天花板 ' '
  • 假設垂直位置 y 介於 nCeilingnFloor 之間 -> 渲染牆壁 #
  • 假設垂直位至 y 大於 nFloor -> 渲染地板 ' '
for (int y = 0; y < nScreenHeight; y++)
{
    if (y < nCeiling) // If the pixel is above the nCeiling -> should be ceiling
    {
        screen[y * nScreenWidth + x] = ' '; // Set to space
    }
    else if (y > nCeiling && y <= nFloor) // If the pixel is between the nCeiling and nFloor -> should be wall
    {
        screen[y * nScreenWidth + x] = '#'; // Set to wall character
    }
    else // If the pixel is below the nFloor -> should be floor
    {
        screen[y * nScreenWidth + x] = ' '; // Set to floor character
    }
}

上一篇
Day 14 | Ray Casting : 光如何前進? Part 3
下一篇
Day 16 | Ray Casting : 距離決定牆壁的高矮 - Part 2
系列文
用 C++ 實作簡易第一人稱視角遊戲:從入門到理解 Ray Casting30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言